package com.sqmf.util;


import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;


/*
 * 利用HttpClient进行post请求的工具类
 */
public class HttpClientUtil {

    private final static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    public static String doPost(String url, String jsonStr, Integer connTimeout, Integer readTimeout) {
        logger.info("*********************请求第三方API POST**************************");
        final long startTime = System.currentTimeMillis();
        logger.info("请求地址:" + url);
        logger.info("请求参数:" + jsonStr);
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        String result = "";
        try {
            StringEntity s = new StringEntity(jsonStr, ContentType.APPLICATION_JSON);
            post.setHeader("Content-Type","application/json");
           // post.setHeader("Authorization","YWRtaW46WDF1aXFza0ZySUxwTGRJcw==");
            post.setEntity(s);
            RequestConfig.Builder custom = RequestConfig.custom();
            if (connTimeout != null) {
                custom.setConnectTimeout(connTimeout);
            }
            if (readTimeout != null) {
                custom.setSocketTimeout(readTimeout);
            }
            post.setConfig(custom.build());
            HttpResponse res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(res.getEntity(), "UTF-8");// 返回json格式
                logger.info("响应结果:" + result);
            } else {
                throw new IllegalArgumentException("调用失败:" + res.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            logger.info("Get Error Occured!");
            e.printStackTrace();
        }
        logger.info("finish to restfulPost used time is:" + (System.currentTimeMillis() - startTime));
        return result;
    }


    public static URLConnection getConnection(String s) throws IOException {
        URL url = new URL(s);
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
        conn.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
        return conn;
    }

    public static String reqPost(String url, String param) throws IOException {
        logger.info("请求地址:" + url);
        logger.info("请求参数:" + param);
        BufferedReader reader = null;
        String sb = null;
        OutputStreamWriter wr = null;
        try {
            URLConnection conn = getConnection(url);
            conn.setDoOutput(true);
            conn.setConnectTimeout(1000 * 5);
            if (param != null && param.toString().trim().length() > 0) {
                wr = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
                wr.write(param.toString());
                wr.flush();
            }
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            sb = new String();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb += (line + "\n");
            }

        } catch (Exception e) {
            logger.info("Get Error Occured!");
            e.printStackTrace();
        } finally {
            try {
                if (wr != null) {
                    wr.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb;
    }
}